package com.hang.gymmanager.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hang.gymmanager.Enum.ImgTypeEnum;
import com.hang.gymmanager.Enum.PlaceUseRecordStatusEnum;
import com.hang.gymmanager.Enum.PlaceUseRecordTypeEnum;
import com.hang.gymmanager.convert.PojoConvert;
import com.hang.gymmanager.entity.PlaceEntity;
import com.hang.gymmanager.entity.PlaceUseRecordEntity;
import com.hang.gymmanager.exception.BusinessException;
import com.hang.gymmanager.mapper.PlaceMapper;
import com.hang.gymmanager.mapper.PlaceUseRecordMapper;
import com.hang.gymmanager.req.ReserveDetailReq;
import com.hang.gymmanager.req.ReservePlaceReq;
import com.hang.gymmanager.req.UpdatePlaceReq;
import com.hang.gymmanager.res.AbleDateRes;
import com.hang.gymmanager.res.PlaceDetailActRes;
import com.hang.gymmanager.res.PlaceDetailRes;
import com.hang.gymmanager.res.ReserveDetailRes;
import com.hang.gymmanager.service.PlaceService;
import com.hang.gymmanager.service.PlaceUseRecordService;
import com.hang.gymmanager.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.hang.gymmanager.Enum.CommonConstant.LINUX_PATH;

@Service
@Slf4j
@RequiredArgsConstructor
public class PlaceServiceImpl extends ServiceImpl<PlaceMapper, PlaceEntity> implements PlaceService {

    private final PojoConvert pojoConvert;
    private final PlaceUseRecordService placeUseRecordService;
    private final PlaceUseRecordMapper placeUseRecordMapper;

    @Override
    public List<PlaceEntity> getAllPlaces() {
        QueryWrapper<PlaceEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().orderByAsc(PlaceEntity::getPlaceId);
        List<PlaceEntity> list = this.getBaseMapper().selectList(wrapper);
        return list;
    }

    @Override
    public PlaceDetailRes getPlaceDetail(Integer placeId) {
        PlaceEntity placeEntity = this.getBaseMapper().selectById(placeId);
        PlaceDetailRes res = new PlaceDetailRes();
        BeanUtils.copyProperties(placeEntity,res);
        LocalTime startTime = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0).toLocalTime();
        LocalTime endTime = LocalDateTime.now().plusDays(1).withHour(0).withMinute(0).withSecond(0).plusSeconds(-1).toLocalTime();
        LocalDate day = LocalDate.now();
        List<PlaceDetailActRes> info = this.getBaseMapper().getPlaceDetail(placeId,day,startTime,endTime);
        res.setRelateActivity(info);
        return res;
    }

    @Override
    public void updatePlaceDetail(UpdatePlaceReq req) {
        PlaceEntity placeEntity = new PlaceEntity();
        placeEntity.setPlaceId(req.getPlaceId());
        placeEntity.setPlaceName(req.getPlaceName());
        placeEntity.setIntroduce(req.getIntroduce());
        placeEntity.setPlaceType(req.getPlaceType());
        this.getBaseMapper().updateById(placeEntity);
    }

    @Override
    public void uploadPic(MultipartFile file,Integer placeId) {
        //如果文件为空 报错
        if (file.isEmpty()) {
            throw new BusinessException("文件为空");
        }
        try {
            //获取项目当前路径
//            String url = "D:\\ideaProject";
            String url = LINUX_PATH;
            Path imgPath = Paths.get(url,"img");
            //获取文件字节流文件
            byte[] bytes = file.getBytes();
            //文件id
            String fileName = ImgTypeEnum.PLACE.getValue()+"-"+placeId+".jpg";
            // 构建保存文件的路径
            Path filePath = imgPath.resolve(fileName);
            // 将文件保存到本地
            Files.write(filePath, bytes);
            //场地图片地址存储
            PlaceEntity placeEntity = this.getBaseMapper().selectById(placeId);
            placeEntity.setImgPath(fileName);
            this.saveOrUpdate(placeEntity);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Override
    public List<AbleDateRes> getAbleDate(Integer placeId) {
        Map<String,String> map = new HashMap<>();
        map.put("MONDAY", "星期一");
        map.put("TUESDAY", "星期二");
        map.put("WEDNESDAY", "星期三");
        map.put("THURSDAY", "星期四");
        map.put("FRIDAY", "星期五");
        map.put("SATURDAY", "星期六");
        map.put("SUNDAY", "星期日");
        List<LocalDate> dates = placeUseRecordMapper.getAbleDate(placeId,LocalDate.now());
        List<AbleDateRes> res = new ArrayList<>();
        dates.stream().forEach(e->{
            AbleDateRes temp = new AbleDateRes();
            temp.setDate(e);
            DayOfWeek dayOfWeek = e.getDayOfWeek();
            temp.setDayOfWeek(map.get(dayOfWeek.toString()));
            res.add(temp);
        });
        return res;
    }


    @Override
    public ReserveDetailRes reserveDetail(ReserveDetailReq req) {
        //先查询场地信息
        Integer placeId = req.getPlaceId();
        LocalDate day = req.getDay();
        ReserveDetailRes res = new ReserveDetailRes();
        res.setPlace(this.getBaseMapper().selectById(placeId));
        QueryWrapper<PlaceUseRecordEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(PlaceUseRecordEntity::getPlaceId,placeId)
                .eq(PlaceUseRecordEntity::getDay,day)
                .orderByAsc(PlaceUseRecordEntity::getStartTime);
        List<PlaceUseRecordEntity> list = placeUseRecordService.getBaseMapper()
                .selectList(wrapper);
        res.setRecords(list);
        return res;
    }

    @Override
    public void reserve(ReservePlaceReq req) {
        //还是要看看是不是分片已经被占用了
        PlaceUseRecordEntity record = placeUseRecordService.getBaseMapper().selectById(req.getPlaceUseRecordId());
        if(record.getStatus()!=PlaceUseRecordStatusEnum.FUTURE.getValue()){
            throw new BusinessException("该时段已经被占用了");
        }
        Integer userId = SecurityUtils.getUserId();
        record.setRelationId(userId);
        record.setType(PlaceUseRecordTypeEnum.PERSONAL.getValue());
        record.setStatus(PlaceUseRecordStatusEnum.OCCUPY.getValue());
        placeUseRecordService.saveOrUpdate(record);
    }
}
